package com.Telien.app.ui.main;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import com.Teilen.app.db.main.DBWrapper;
import com.Telien.app.Telien;
import com.Telien.app.request.object.DriverRequest;
import com.Telien.app.request.object.rideService;
import com.Telien.app.request.service.RequestService;
import com.Telien.app.user.object.User;
import com.Telien.app.user.service.SessionManagementService;
import com.Telien.app.user.service.UserManagementService;

public class RequestTablePanel extends JPanel implements ActionListener, TableModelListener {
	private RequestService requestService;
	private UserManagementService ums;
	private	JTable		table;
	private	JScrollPane scrollPane;
	private JPopupMenu popupMenu;
	private JMenuItem requestItem;
	//private JMenuItem viewItem;
	private JMenuItem refreshItem;
	private RequestSearchPanel rsp;
	GridLayout experimentLayout = new GridLayout(3,0);
	private DBWrapper db = new DBWrapper();
	private User user;
	private DefaultTableModel model;
	
	//Search Panel
	private JPanel searchPanel;
	private JLabel findLabel;
	private JTextField findTextField;
	private JButton enterButton;
	
	private static String columnNames[] = { "Driver Username", "Seats Available", "Departure Time","Arrival Time","Start Location","End Location"};
	//Object dataValues[][] =
		//{
			//{ "Juwan Staten", "2", "12:00PM","12:00AM","POINT( 34,12,)","POINT( 34,12,)"},
			//{ "Chase Connor ", "3", "12:00PM","12:00AM","POINT( 34,12,)","POINT( 34,12,)"},
			//{ "Jevon Carter ", "7", "12:00PM","12:00AM","POINT( 34,12,)","POINT( 34,12,)"}
	//	};
	Object dataValues[][] = {
			{"", "", "", "", "", ""}
	};
	private ArrayList<DriverRequest> requests = new ArrayList<DriverRequest>();	
		
	public RequestTablePanel(User user) {
		this.user = user;
		
		DBWrapper db = new DBWrapper();
		
		ums = new UserManagementService();
		requests = db.getAllDriverRequests();
		//addTestData();
		
		if (requests != null) {
		
		dataValues = new Object [requests.size()][6];
		ums.loadUsersFromDb();
		if (!requests.isEmpty()) {
			for (int numRequests = 0; numRequests < requests.size(); numRequests++) {
					
					dataValues[numRequests][0] = ums.getUserNameMem(requests.get(numRequests).getUserUUID());
					//dataValues[numRequests][0] = requests.get(numRequests).getUserUUID();
					dataValues[numRequests][1] = requests.get(numRequests).getPassanagerCount() + "";
					dataValues[numRequests][2] = requests.get(numRequests).getStartTime().toString();
					dataValues[numRequests][3] = requests.get(numRequests).getEndTime().toString();
					dataValues[numRequests][4] = requests.get(numRequests).getStartCord().toString();
					dataValues[numRequests][5] = requests.get(numRequests).getEndCord().toString();
				}
			}
		}
		
		this.initialize();
	}
	
	private void initialize() {			
		//setLayout(experimentLayout);
		setLayout(new BorderLayout());
		model = new DefaultTableModel(dataValues, columnNames);
		table = new JTable(model);
		scrollPane = new JScrollPane(table);
		popupMenu = new JPopupMenu();
		requestItem = new JMenuItem("Add Request");
		//viewItem = new JMenuItem("View Information");
		refreshItem = new JMenuItem("Refresh Page");
		requestItem.addActionListener(this);
		//viewItem.addActionListener(this);
		refreshItem.addActionListener(this);
		popupMenu.add(requestItem);
		//popupMenu.add(viewItem);
		popupMenu.add(refreshItem);
        table.setComponentPopupMenu(popupMenu);
        //rsp = new RequestSearchPanel("driver",table);
        //add(rsp,BorderLayout.NORTH);
        searchPanel = new JPanel();
          
        FlowLayout experimentLayout = new FlowLayout();
        searchPanel.setLayout(experimentLayout);
		findLabel = new JLabel("Search:");
		findTextField = new JTextField(30);
		enterButton = new JButton("Enter");
		enterButton.addActionListener(this);
		searchPanel.add(findLabel);
		searchPanel.add(findTextField);
		searchPanel.add(enterButton);
      
        add(searchPanel,BorderLayout.NORTH);
		add(scrollPane, BorderLayout.CENTER);
			
		setVisible(true);
	}
	
	private void addTestData() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		DriverRequest r1 = new DriverRequest(1, 1, "1", "1", "1", "1", 1, 1, 1, null, null);
		DriverRequest r2 = new DriverRequest(2, 2, "2", "2", "2", "2", 2, 2, 2, null, null);
		DriverRequest r3 = new DriverRequest(3, 3, "3", "3", "3", "3", 3, 3, 3, null, null);
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
		String dateInString = "31-08-1982 10:20:56";
		Date StartTime;
			try {
				StartTime = sdf.parse(dateInString);
				r1.setStartTime(StartTime);
				r2.setStartTime(StartTime);
				r3.setStartTime(StartTime);
				r1.setEndTime(StartTime);
				r2.setEndTime(StartTime);
				r3.setEndTime(StartTime);
			} catch (ParseException e) {}
		
		r1.setUserUUID("1");
		r2.setUserUUID("2");
		r3.setUserUUID("3");
		
		requests.add(r1);
		requests.add(r2);
		requests.add(r3);
	}

	
	
	public void actionPerformed(ActionEvent e) {
		String name = e.getActionCommand();
		if (name.equals("Add Request")) {
			System.out.println("Add Request");
			if (table.getSelectedRow() != -1) {
				DriverRequest request = requests.get(table.getSelectedRow());				
				int rideSessionId = db.selectSessionsSize(); //how  do it get this, get the size bro
				//int rideSessionId = (int) Math.random();

				try {					
					rideService rs = new rideService(rideSessionId, Integer.parseInt(request.getUserUUID()), Integer.parseInt(user.getUserUUID()), request.getStartTime(), false, request);
					db.createSession(rs);
				}
				catch (NumberFormatException nfe) {
					System.out.println("COULD NOT PARSE BECAUSE IDS ARE NOT INTS");
					nfe.printStackTrace();
				}
				Telien.getMainFrame().addToMyRequests(request, rideSessionId);
				//add ride session table to DB
				//createSession with rideService
				//TODO
			}
		}
		if (name.equals("Refresh Page")) {
			//TODO
			//Telien.getMainFrame().refreshRequestPanel();
			searchTable(findTextField.getText());
		}
		
		if(name.equals("Enter")){
			System.out.println("Search");
			searchTable(findTextField.getText());
		}
	}
	
	private void searchTable(String searchterm){
		requestService = new RequestService();
		ArrayList<DriverRequest> requests = requestService.searchDriverRequest(searchterm);
		System.out.println("requests that meet search criteria:"+requests.size());
		Object dataValues[][] = null;
		//ums.loadUsersFromDb();
		if (requests != null) {
			dataValues = new Object [requests.size()][6];
			if (!requests.isEmpty()) {
				for (int numRequests = 0; numRequests < requests.size(); numRequests++) {
						dataValues[numRequests][0] = ums.getUserName(requests.get(numRequests).getUserUUID());
						//dataValues[numRequests][0] = requests.get(numRequests).getUserUUID();
						dataValues[numRequests][1] = requests.get(numRequests).getPassanagerCount() + "";
						dataValues[numRequests][2] = requests.get(numRequests).getStartTime().toString();
						dataValues[numRequests][3] = requests.get(numRequests).getEndTime().toString();
						dataValues[numRequests][4] = requests.get(numRequests).getStartCord().toString();
						dataValues[numRequests][5] = requests.get(numRequests).getEndCord().toString();
					}
				}
			}
		if(dataValues !=null){
			model = new DefaultTableModel(dataValues, columnNames);
			table.setModel(model);
		}
		
	}

	public void tableChanged(TableModelEvent arg0) {
		System.out.println("Table Changed");
		
	}

}
